import {Component, OnInit} from '@angular/core';
import {Globals} from '../../../globals';
import {PageHelper} from '../../../utils/page-helper-model';
import {FormBuilder} from '@angular/forms';
import {BaseService} from '../../../shared/service/base.service';
import {MyDateModel} from '../../../models/my-date.model';
import {ApiUrl} from '../../../config/api-url';
import {RoleIdEnum} from "../../../enums/role-id.enum";
import {Consts} from "../../../config/consts";
import {Observable} from 'rxjs';

@Component({
  selector: 'app-store-statistic',
  templateUrl: './store-statistic.component.html',
  styleUrls: ['./store-statistic.component.less']
})
export class StoreStatisticComponent implements OnInit {

  isMobile = Globals.isMobile();
  // 分页
  pageHelper: PageHelper = new PageHelper;

  listOfData: any;
  // 开始日期类型
  startDateTimeType = 'start';
  // 结束日期类型
  endDateTimeType = 'end';
  // 开始日期
  startDateTime: Date;
  // 结束日期
  endDateTime: Date;
  isCollapse = true;
  // 日月数据统计按钮样式
  day = 'primary';
  month = 'default';
  type = 1;
  userInfo: any;
  userId:any;
  merchantStoreId:any;
  // 运营商
  userList: [];
  // 门店
  merchantStoreList: [];
  roleIdEnum = {
    SUPER_ADMINISTRATOR: RoleIdEnum.SUPER_ADMINISTRATOR,
    AGENT: RoleIdEnum.AGENT,
  };

  constructor(private baseService: BaseService,
              private fb: FormBuilder) {

  }

  ngOnInit(): void {
    this.userInfo = JSON.parse(sessionStorage.getItem(Consts.USER_INFO));
    this.startDateTime = this.baseService.zorro.getDateTime().startYesterday;
    this.endDateTime = this.baseService.zorro.getDateTime().endYesterday;
    this.findData();
    this.getAllUserOfName();
    this.findAllMerchantStoreByUserInfo();
  }
  findAllMerchantStoreByUserInfo() {
    let userId = null;
    if (this.userId != null) {
      userId = userId;
    } else {
      userId = '';
    }
    this.baseService.get(ApiUrl.MerchantStoreUrl + '/findAllMerchantStoreByUserInfo?userId=' + userId).subscribe(
      data => {
        if (data.status == 0) {
          this.merchantStoreList = data.data;
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }
  getAllUserOfName() {
    this.baseService.get(ApiUrl.UserUrl + '/getAllUserOfName?agencyId=0').subscribe(data => {
      if (data.status == 0) {
        this.userList = data.data;
      } else {
        this.baseService.layer.messageError(data.msg);
      }
    });
  }
  // 将开始、结束时间往外抛
  outDateTime($event: MyDateModel) {
    /**
     * date: Fri Mar 19 2021 23:59:06 GMT+0800 (中国标准时间) {}
     * type: "end"
     */
    if ($event.type == 'start') {
      this.startDateTime = $event.date;
    } else if ($event.type == 'end') {
      this.endDateTime = $event.date;
    }
  }

  onStartMonth($event) {
    this.startDateTime = $event;
  }

  onEndMonth($event: any) {
    this.endDateTime = $event;
  }


  nzPageIndexChange($event: number) {
    this.pageHelper.currentPage = $event;
    this.findData();
  }
  onPageSizeChange(pageSize: any){
    this.pageHelper.pageSize = pageSize;
    this.pageHelper.currentPage = 1;
    this.findData();
  }
  findData() {
    const body = {
      createTime: this.startDateTime,
      updateTime: this.endDateTime,
      keyword: this.pageHelper.keyword.trim(),
      type: this.type,
      userId:this.userId,
      mchStoreId:this.merchantStoreId,
    };
    this.baseService.findListByMuchCondition(ApiUrl.StatsStoreUrl + '/list', body, this.pageHelper).subscribe(
      data => {
        if (data.status == 0) {
          this.pageHelper.totalItems = data.data.total;
          this.listOfData = data.data.list;
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }
  exportCsv() {
    if (this.startDateTime == null || this.endDateTime == null) {
      this.baseService.layer.messageError('请选择订单时间!');
      return null;
    }
    this.baseService.layer.modalConfirm('确定导出数据吗？', confirm => {
      if (confirm) {
        const body = {
          createTime: this.startDateTime,
          updateTime: this.endDateTime,
          keyword: this.pageHelper.keyword.trim(),
          type: this.type,
          userId:this.userId,
          mchStoreId:this.merchantStoreId,
        };
        this.baseService.post(ApiUrl.StatsStoreUrl + '/exportStatsStoreList', body).subscribe(
          res => {
            // console.log('数据导出返回值', res);
            if (res.status == 0) {
              this.export(res.data.downloadUrl, res.data.fileName);
            } else {
              this.baseService.layer.messageError(res.msg);
            }
          }
        );
      }
    });
  }
  // Blob文件转换下载
  export(url: any, fileName: string, fileType?: any) {
    this.requestBlob(url, {}).subscribe(result => {
      this.downFile(
        result,
        fileName,
        fileType ||
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      );
    });
  }
  downFile(result, fileName, fileType?) {
    const data = result.body;
    const blob = new Blob([data], {type: fileType || data.type});
    const objectUrl = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.setAttribute('style', 'display:none');
    a.setAttribute('href', objectUrl);
    a.setAttribute('download', fileName);
    a.click();
    URL.revokeObjectURL(objectUrl);
  }
  requestBlob(url: any, data?: any): Observable<any> {
    return this.baseService.http.request('post', url, {
      body: data,
      observe: 'response',
      responseType: 'blob',
    });
  }

  search() {
    this.pageHelper.currentPage = 1;
    this.findData();
  }

  dayMethod() {
    this.startDateTime = this.baseService.zorro.getDateTime().startYesterday;
    this.endDateTime = this.baseService.zorro.getDateTime().endYesterday;
    this.pageHelper.currentPage = 1;
    this.type = 1;
    this.findData();
    this.day = 'primary';
    this.month = 'default';
  }

  monthMethod() {
    this.startDateTime = this.baseService.zorro.getDateTime().startLastMonth;
    this.endDateTime = this.baseService.zorro.getDateTime().endLastMonth;
    this.pageHelper.currentPage = 1;
    this.type = 2;
    this.findData();
    this.day = 'default';
    this.month = 'primary';
  }

}
